﻿using Framework;
using UnityEngine;

namespace View
{
    public class ViewProxy
    {
        protected GameObject _goContainer;
        protected RectTransform _transfContainer;

        protected GameObject _gameObject;
        protected RectTransform _transform;

        protected GameObject _mainAsset;
        protected GameObject[] _subAssets;

        public ViewProxy()
        {
            _goContainer = new GameObject("ViewProxy", typeof(RectTransform));
            _transfContainer = (RectTransform) _goContainer.transform;

            _transfContainer.anchorMin = Vector2.zero;
            _transfContainer.anchorMax = Vector2.one;
            _transfContainer.offsetMin = Vector2.zero;
            _transfContainer.offsetMax = Vector2.zero;
            
            SetupView();
        }

        public void Dispose()
        {
            OnDispose();
            GameObject.Destroy(_goContainer);
        }

        public void Show()
        {
            UILayer layer = UILayerManager.instance.GetLayer(UILayerName.View);
            layer.AddChild(_transfContainer, false);
        }

        public void Close()
        {
            UILayer layer = UILayerManager.instance.GetLayer(UILayerName.View); 
            layer.RemoveChild(_transfContainer);
            Dispose();
        }

        protected virtual void SetupView()
        {
            
        }

        protected void LoadRes(string asset, string[] subAssets = null)
        {
            _mainAsset = Resources.Load<GameObject>(asset);
            if (subAssets != null)
            {
                _subAssets = new GameObject[subAssets.Length];
                for (int i = 0; i < subAssets.Length; ++i)
                {
                    GameObject subAsset = Resources.Load<GameObject>(subAssets[i]);
                    _subAssets[i] = subAsset;
                } 
            }

            _gameObject = GameObject.Instantiate(_mainAsset);
            _transform = (RectTransform) _gameObject.transform;
            _transform.SetParent(_transfContainer, false);
            
            OnInit();
        }

        protected virtual void OnInit()
        {
            
        }

        protected virtual void OnDispose()
        {
            
        }
    }
}